package com.hkc.huakang.hkcpaperless;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.hkc.huakang.hkcpaperless.bin.ChannelList;
import com.hkc.huakang.hkcpaperless.bin.OrderDetail;
import com.hkc.huakang.hkcpaperless.bin.OutOrderDetail;
import com.mysql.jdbc.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class ListViewActivity extends AppCompatActivity implements Runnable {
    private ExpandableListView expandList;
    private List<String> groupData;//group的数据源
    private Map<Integer, List<ChildItem>> childData;//child的数据源
    private OrderDetailsAdapter myAdapter;
    List<OrderDetail> list;
    TextToSpeech tts;
    RecyclerView rv;
    TextView disease, userName, userSex, userAge, orderNo, yk_tv;
    String CuttentOrder_group_no;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            return false;
        }
    });
    boolean  isNewOrderGroupNum=false;
    MysqlConnectUtil mysqlConnectUtil;
    boolean   isSpeek=true,isFnish=false,isAdapterNotify=true;
    Dialog  loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        myAdapter = new OrderDetailsAdapter(this);
        disease = findViewById(R.id.disease);
        userName = findViewById(R.id.user_name);
        userSex = findViewById(R.id.user_sex);
        userAge = findViewById(R.id.user_age);
        orderNo = findViewById(R.id.order_no);
        yk_tv = findViewById(R.id.yk_tv);
        rv = (RecyclerView) findViewById(R.id.recycler_view);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(myAdapter);
        mysqlConnectUtil = new MysqlConnectUtil();
        getDisposeOrder();
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    // 初始化成功，可以开始使用TTS
                    int result = tts.setLanguage(Locale.US); // 设置语言为美国英语

                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        // 语言数据缺失或不支持
                        Log.e("TTS", "This Language is not supported");
                    } else {
                        // 语言设置成功
                        // speak("Hello, this is a text to speech example.");
                    }
                } else {
                    // 初始化失败
                    Log.e("TTS", "Initilization Failed!");
                }
            }
        });
        tts.setPitch(1.0f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        tts.setSpeechRate(1.0f);
        myAdapter.setPositiListener(new OrderDetailsAdapter.OnPositionClickLisntener() {
            @Override
            public void Click(View view, OrderDetail od) {
                handler.removeCallbacks(ListViewActivity.this);
                isAdapterNotify=false;
                view.setClickable(false);
              //  loadingDialog=DialogUtils.getInstance().createLoadingDialog(ListViewActivity.this,"处理中...");
                insertOutMachineDetails(view,od);

            }
        });
    }

    public MysqlConnectResult<List<OrderDetail>> getDisposeOrder() {
        System.out.println("---------getDisposeOrder------>");
        final Exception[] ep = new Exception[1];
        final OrderDetail[] disposeOrders = {new OrderDetail()};
        try {
            final CountDownLatch latch = new CountDownLatch(1); // 使用 CountDownLatch 来等待回调完成
            mysqlConnectUtil.connect(new MysqlConnectUtil.ConnectResult() {
                @Override
                public void onConnectFail(Exception e) {
                    e.printStackTrace();
                    System.out.println("Mysql连接失~~~败！");
                    handler.postDelayed(ListViewActivity.this, 1500); //每隔1s执行
                    latch.countDown();
                    ep[0] = e;
                }

                @Override
                public void onConnectSuccess() {
                    String uName = SharedPreferencesUtils.getInstance().getUserName(ListViewActivity.this);
                    String sql = "SELECT  oi.patient_id, oi.p_name, oi.sex,oi.age, oi.order_no,  oi.in_time,  oi.disease,oi.order_group_no,  od.drug_id,  od.quantity, od.unit_convercoef, od.order_unit, di.big_unit,  di.small_unit,  di.back_stock_pos,di.drug_name,  oi.basket_card,   di.drug_spec," +
                            "    (SELECT dos.win_no  " +
                            "     FROM dispose_order AS dos  " +
                            "     WHERE dos.order_group_no = (  " +
                            "         SELECT dos2.order_group_no  " +
                            "         FROM dispose_order AS dos2  " +
                            "         WHERE dos2.pf_user_name = 'admin'  " +
                            "         AND dos2.pf_flag = '0'  " +
                            "         ORDER BY dos2.pf_user_time   " +
                            "         LIMIT 1  " +
                            "     )  " +
                            "     LIMIT 1) AS win_no    FROM   order_info AS oi   INNER JOIN order_detail AS od ON oi.order_no = od.order_no   INNER JOIN drug_info AS di ON od.drug_id = di.drug_id   WHERE   oi.order_group_no = (   SELECT    dos.order_group_no   FROM  dispose_order AS dos   WHERE    dos.pf_user_name = '" + uName + "'  AND dos.pf_flag = '0'   ORDER BY   dos.pf_user_time DESC    LIMIT 1   )ORDER BY  oi.charge_date DESC ";
                    list = mysqlConnectUtil.getDisposeOrder(sql);
                    for (int i = 0; i < list.size(); i++) {
                        OrderDetail dis = list.get(i);
                        if (i == 0) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!dis.getOrder_group_no().equals(CuttentOrder_group_no)) {
                                        isFnish=false;isSpeek=true;
                                        CuttentOrder_group_no = dis.getOrder_group_no();
                                    }
                                    userSex.setText(dis.getSex());
                                    String ageStr = dis.getAge() == null ? "0" : dis.getAge();
                                    userAge.setText(ageStr + "岁");
                                    userName.setText(dis.getP_name());
                                    disease.setText(dis.getDisease());
                                    orderNo.setText(dis.getOrder_group_no());

                                    yk_tv.setText(dis.getBasket_card() == 10000 ? String.valueOf(0) : String.valueOf(dis.getBasket_card()));

                                }
                            });
                        }

                        // String  sql1="SELECT  machine_id,row_no,col_no,sum(real_quantity) as real_quantity from   machine_out_detl   where   order_no='" + dis.getOrder_no() + "' and drug_id='" + dis.getDrugId() + "' GROUP BY  drug_id";
                        String sql1 = "SELECT ml.machine_name, mot.machine_id, mot.row_no, mot.col_no,sum( mot.real_quantity) as real_quantity , ml.serial_level from   machine_out_detl as  mot left  JOIN  machine_list as ml on mot.machine_id=ml.machine_id where   mot.order_no='" + dis.getOrder_no() + "' and mot.drug_id='" + dis.getDrugId() + "' GROUP BY  mot.drug_id";
                       // System.out.println("药品名称：" + dis.getDrug_name());
                       // System.out.println("出药表查询SQL：" + sql1);
                        OutOrderDetail od = mysqlConnectUtil.getOutOrderDetail(sql1);
                        if (od == null) {
                            //String sql2="SELECT  machine_id,row_no,col_no  from   channel_list   where   drug_id='" + dis.getDrugId() + "' GROUP BY  drug_id";
                            String sql2 = "SELECT ml.machine_name, cl.machine_id,cl.row_no,cl.col_no,ml.serial_level ,(SELECT outpos_no from window_list where win_no="+dis.getWin_no()+") as outpos_no from   channel_list  as cl left  JOIN  machine_list as ml on cl.machine_id=ml.machine_id  where   cl.drug_id='" + dis.getDrugId() + "' GROUP BY  cl.drug_id";
                            //System.out.println("库存查询SQL：" + sql2);
                            ChannelList cl = mysqlConnectUtil.searchGrugPosition(sql2);
                            if (cl != null) {
                                dis.setPosition(cl.getMachine_id() + "-" + cl.getRow_no() + "-" + cl.getCol_no());
                                dis.setMachineName(cl.getMachineName());
                                dis.setMachineID(cl.getMachine_id());
                                dis.setRowN(cl.getRow_no());
                                dis.setSerial_level(cl.getSerial_level());
                                dis.setColN(cl.getCol_no());
                                dis.setOutpos_no(cl.getOutpos_no());
                                dis.setDispatch(false);


                            } else {
                                dis.setMachineName(dis.getBack_stock_pos());
                                dis.setPosition(dis.getBack_stock_pos());
                                dis.setDispatch(false);

                            }

                        } else {
                            dis.setPosition(od.getMachine_id() + "-" + od.getRow_no() + "-" + od.getCol_no());
                            dis.setOutQuantity(od.getReal_quantity());
                            dis.setMachineName(od.getMachineName());
                            dis.setMachineID(od.getMachine_id());
                            dis.setRowN(od.getRow_no());
                            dis.setColN(od.getCol_no());
                            dis.setSerial_level(od.getSerial_level());
                            dis.setDispatch(true);
                        }
                    }
                    List<OrderDetail> list2 = new ArrayList<>();
                    List<OrderDetail> list3 = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        OrderDetail d = list.get(i);
                        if (d.isDispatch()) {
                            list2.add(d);
                        } else {
                            list3.add(d);
                        }
                    }
                    Collections.sort(list2, new Comparator<OrderDetail>() {
                        @Override
                        public int compare(OrderDetail o1, OrderDetail o2) {
                            return Integer.compare(o1.getSerial_level(), o2.getSerial_level());
                        }
                    });
                    Collections.sort(list3, new Comparator<OrderDetail>() {
                        @Override
                        public int compare(OrderDetail o1, OrderDetail o2) {
                            return Integer.compare(o1.getSerial_level(), o2.getSerial_level());
                        }
                    });
                    List<OrderDetail> list1 = new ArrayList<>();
                    list1.addAll(list3);
                    list1.addAll(list2);
                    System.out.println("----list3.size():"+list3.size()+"------isSpee:"+isSpeek);

                    if(list3.size()>0&&isSpeek){
                        System.out.println("---------isSpeek-------->"+isSpeek);
                        isFnish=false;
                        OrderDetail temp=list3.get(0);
                        if(temp.getOutpos_no()!=null&&temp.getMachineID().startsWith("K")){
                            if(temp.getOutpos_no().startsWith("7")){
                                speak("请到"+temp.getMachineName()+" 右侧取药！");
                            }else if(temp.getOutpos_no().startsWith("8")){
                                speak("请到"+temp.getMachineName()+"左侧取药！");
                            }
                        }else{
                            speak("请到"+temp.getMachineName()+"取药！");
                        }
                        isSpeek=!isSpeek;

                    }else if(list3.size()<=0&&!isFnish){
                        System.out.println("配药已完成！");
                        speak("配药已完成！");
                        isFnish=true;
                    }
                    mysqlConnectUtil.onClose();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                         System.out.println("刷新----------->");
                         if(isAdapterNotify){
                             myAdapter.setDate(list1);
                             myAdapter.notifyDataSetChanged();
                         }
                        }
                    });
                    latch.countDown();
                    handler.postDelayed(ListViewActivity.this, 1500); //每隔1s执行
                }
            }, this);
            latch.await(); // 阻塞等待
            if (ep[0] != null) {
                return new MysqlConnectResult.Error(ep[0]);
            }
            return new MysqlConnectResult.Success<>(disposeOrders[0]);
        } catch (Exception e) {
            return new MysqlConnectResult.Error(new IOException("Error logging in", e));
        }
    }

    public MysqlConnectResult<List<OrderDetail>> insertOutMachineDetails(View view,OrderDetail od) {
        final Exception[] ep = new Exception[1];
        final OrderDetail[] disposeOrders = {new OrderDetail()};
        try {
            final CountDownLatch latch = new CountDownLatch(1); // 使用 CountDownLatch 来等待回调完成
            mysqlConnectUtil.connect(new MysqlConnectUtil.ConnectResult() {
                @Override
                public void onConnectFail(Exception e) {
                    view.setClickable(true);
                    handler.postDelayed(ListViewActivity.this, 0); //每隔1s执行
                    e.printStackTrace();
                    System.out.println(" insertOutMachineDetails Mysql连接失~~~败！");
                    latch.countDown();
                    ep[0] = e;
                }

                @Override
                public void onConnectSuccess() {

                    String machineid = od.getMachineID() == null ? od.getBack_stock_pos() : od.getMachineID();
                    String sql = "INSERT INTO machine_out_detl (machine_id,row_no, col_no,  patient_id, p_name, order_no, order_no_s,  drug_id,  real_quantity,  confirm_flag, confirm_time )  VALUES ('" + machineid + "','" + od.getRowN() + "', '" + od.getColN() + "', '" + od.getPatient_id() + "', '" + od.getP_name() + "', '" + od.getOrder_no() + "', '" + od.getOrder_no() + "', '" + od.getDrugId() + "', '" + od.getQuantity() + "', '1', NOW());";
                    System.out.println("数据插入Sql！：" + sql);
                    boolean res = mysqlConnectUtil.insertOutMachineDetails(sql);
                    if(res){
                      isSpeek=!isSpeek;
                    }
                    mysqlConnectUtil.onClose();
                    handler.postDelayed(ListViewActivity.this, 0); //每隔1s执行
                    isAdapterNotify=true;
                    System.out.println("  Dialog  关闭！！");
                    latch.countDown();
                }
            }, this); 
            latch.await(); // 阻塞等待

            if (ep[0] != null) {
                return new MysqlConnectResult.Error(ep[0]);
            }
            return new MysqlConnectResult.Success<>(disposeOrders[0]);
        } catch (Exception e) {
            return new MysqlConnectResult.Error(new IOException("Error logging in", e));
        }
    }

    public MysqlConnectResult<List<OrderDetail>> getOrderDetail(String orderGroupNo) {

        final Exception[] ep = new Exception[1];
        final OrderDetail[] OrderDetail = {new OrderDetail()};
        final List<OrderDetail>[] list = new ArrayList[1];
        try {
            final CountDownLatch latch = new CountDownLatch(1); // 使用 CountDownLatch 来等待回调完成
            MysqlConnectUtil mysqlConnectUtil = new MysqlConnectUtil();
            mysqlConnectUtil.connect(new MysqlConnectUtil.ConnectResult() {
                @Override
                public void onConnectFail(Exception e) {
                    System.out.println("连接失败！");
                    latch.countDown();
                    ep[0] = e;
                }

                @Override
                public void onConnectSuccess() {
                    // list[0] = mysqlConnectUtil.getOrderDetails("  SELECT * from   order_detail as a LEFT JOIN  drug_info as b ON a.drug_id=b.drug_id where ( select  order_group_no from  order_info a  WHERE order_group_no='"+orderGroupNo+"') ");
                    // list[0] = mysqlConnectUtil.getOrderDetails("  SELECT * from   order_detail as a LEFT JOIN  drug_info as b ON a.drug_id=b.drug_id where a.order_no in( select  order_no from  order_info a  WHERE order_group_no='"+orderGroupNo+"')  ");
                    latch.countDown();
                }
            }, this);
            latch.await(); // 阻塞等待
            if (ep[0] != null) {
                return new MysqlConnectResult.Error(ep[0]);
            }
            return new MysqlConnectResult.Success<>(list[0]);
        } catch (Exception e) {
            return new MysqlConnectResult.Error(new IOException("Error logging in", e));
        }
    }

    private void speak(String text) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator.hasVibrator()) {
            long[] pattern = {0, 200, 100, 200};
            vibrator.vibrate(pattern, -1);
            // 或者指定重复次数，比如vibrate(pattern, 1);
        }
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
    }
    public static String getProcessName_2(Context context) {
        // 获取此进程的标识符
        int pid = android.os.Process.myPid();
        // 获取活动管理器
        ActivityManager activityManager = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
        // 从应用程序进程列表找到当前进程，是：返回当前进程名
        for (ActivityManager.RunningAppProcessInfo appProcess :
                activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    public void run() {
        getDisposeOrder();
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(ListViewActivity.this);

        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
}